
/*
 * IMPORTANT NOTE: As an example it is, the process created for the server
 * is not killed when exiting the program, it will be implemented during the
 * integration in our application. Remember to kill the process when exiting
 * the application manually.
 */
package server;

import java.io.InputStream;

/**
 *
 * @author BeTo
 */
public class videoserverp2p {

    String VLCroute, filepath, ipdest, port;

    public videoserverp2p(String VLCroute, String filepath, String ipdest, String port) {
        this.VLCroute = VLCroute + " -I default ";
        this.ipdest = ipdest;
        this.port = port;
        this.filepath = filepath;
    }

    public void sendvideo() {
        try {

            String cmdArray = VLCroute + filepath + " --sout=#rtp{dst=" + ipdest + ",port=" + port + ",mux=ts}";

            /*At this point we create a new process to execute the command
             * needed to execute a new P2P VLC server
             */
            final Process send = Runtime.getRuntime().exec(cmdArray);

            /*We create two new Threads to control the execution of the Process
             * showing out the errors and inputs it has. Finally, we make the
             * program wait until the Process finish.
             */
            new Thread() {

                public void run() {
                    try {
                        InputStream is = send.getInputStream();
                        byte[] buffer = new byte[1024];
                        for (int count = 0; (count = is.read(buffer)) >= 0;) {
                            System.out.write(buffer, 0, count);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            new Thread() {

                public void run() {
                    try {
                        InputStream is = send.getErrorStream();
                        byte[] buffer = new byte[1024];
                        for (int count = 0; (count = is.read(buffer)) >= 0;) {
                            System.err.write(buffer, 0, count);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();

            int returnCode = send.waitFor();
            System.out.println("Return code = " + returnCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
